<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Widgets in Java SWT</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, SWT, Widgets, Java, programming, linux">
<meta name="description" content="In this part of the Java SWT tutorial, we introduce
some widgets.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Widgets in SWT</h1>

<p>
In this part of the Java SWT programming tutorial, we will introduce some SWT widgets.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
Widgets are basic building blocks of a GUI application. Think of widgets as parts
of a lego.
Over the years, several widgets became a standard in all toolkits on all OS platforms. 
For example a button, a check box or a scroll bar. 
</p>


<h2>Label</h2>

<p>
A <code>Label</code> widget shows text. 
</p>


<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;


/**
 * ZetCode Java SWT tutorial
 *
 * This program uses the Label widget to
 * show lyrics of a song
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */


public class SWTApp {

    Shell shell;

    String lyrics =
"And I know that he knows I'm unfaithful\n"+
"And it kills him inside\n"+
"To know that I am happy with some other guy\n"+
"I can see him dyin'\n"+
"\n"+
"I don't wanna do this anymore\n"+
"I don't wanna be the reason why\n"+
"Every time I walk out the door\n"+
"I see him die a little more inside\n"+
"I don't wanna hurt him anymore\n"+
"I don't wanna take away his life\n"+
"I don't wanna be...A murderer";



    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Unfaithful");

        initUI();

        
        shell.pack();
        shell.setLocation(300, 300);
        shell.open();
        

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }


    public void initUI() {

        Label label = new Label(shell, SWT.LEFT);
        label.setText(lyrics);
        
        Point p = label.computeSize(SWT.DEFAULT, SWT.DEFAULT);
        label.setBounds(5, 5, p.x+5, p.y+5);
    }


    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
The code example shows some lyrics on the window. 
</p>

<pre class="explanation">
    String lyrics =
"And I know that he knows I'm unfaithful\n"+
"And it kills him inside\n"+
...
</pre>

<p>
We build a multiline text. 
</p>

<pre class="explanation">
Label label = new Label(shell, SWT.LEFT);
label.setText(lyrics);
</pre>

<p>
The <code>Label</code> widget is created. Text is left aligned.
</p>

<pre class="explanation">
Point p = label.computeSize(SWT.DEFAULT, SWT.DEFAULT);
label.setBounds(5, 5, p.x+5, p.y+5);
</pre>

<p>
We compute the size of the text in order put some space round
the text. 
</p>

<img src="/img/gui/swt/lyrics.png" alt="Label Widget">
<div class="figure">Figure: Label Widget</div>


<h2>CheckButton</h2>

<p>
In SWT, check button is a special case of a <code>Button</code>. It is a widget, 
that has two states. On and Off. The On state is visualised by a check mark. It is used
to denote some boolean property.
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program uses a check button
 * widget to show/hide the title
 * of the window
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */


public class SWTApp {

    private Shell shell;
    private Button cb;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Check button");

        initUI();

        shell.setSize(250, 200);
        shell.setLocation(300, 300);

        shell.open();
        
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }


    public void initUI() {

        cb = new Button(shell, SWT.CHECK);
        cb.setText("Show title");
        cb.setSelection(true);
        cb.setLocation(50, 50);
        cb.pack();


        cb.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                if (cb.getSelection()) {
                    shell.setText("Check button");
                } else {
                    shell.setText("");
                }
            }
        });
    }


    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
We will display a title in the titlebar of the window,
depending on the state of the check button.
</p>

<pre class="explanation">
cb = new Button(shell, SWT.CHECK);
cb.setText("Show title");
</pre>

<p>
<code>CheckButton</code> widget is created. 
</p>

<pre class="explanation">
cb.setSelection(true);
</pre>

<p>
The title is visible by default, so we check the check button by default. 
</p>


<pre class="explanation">
if (cb.getSelection()) {
    shell.setText("Check button");
} else {
    shell.setText("");
}
</pre>

<p>
Depending on the state of the <code>CheckButton</code>, we show or hide the title
of the window. 
</p>

<img src="/img/gui/swt/checkbutton.png" alt="CheckButton">
<div class="figure">Figure: CheckButton</div>



<h2>List widget</h2>

<p>
The next example introduces the <code>List</code> widget.
This widget enables a user to select an option from a list of items.
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program shows the List
 * widget
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */


public class SWTApp {

    Shell shell;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("List");

        initUI();

        shell.setSize(300, 250);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }


    public void initUI() {


        final Label status = new Label(shell, SWT.BORDER);
        status.setText("Ready");
        
        FormLayout layout = new FormLayout();
        shell.setLayout(layout);

        FormData labelData = new FormData();
        labelData.left = new FormAttachment(0);
        labelData.right = new FormAttachment(100);
        labelData.bottom = new FormAttachment(100);
        status.setLayoutData(labelData);

        final List list = new List(shell, SWT.BORDER);
        
        list.add("Aliens");
        list.add("Capote");
        list.add("Neverending story");
        list.add("Starship troopers");
        list.add("Exorcist");
        list.add("Omen");

        list.addListener(SWT.Selection, new Listener () {
            public void handleEvent (Event e) {
                String[] items = list.getSelection();
                status.setText(items[0]);
            }
        });


        FormData listData = new FormData();
        listData.left = new FormAttachment(shell, 30, SWT.LEFT);
        listData.top = new FormAttachment(shell, 30, SWT.TOP);
        list.setLayoutData(listData);
    }


    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
In this example, the selected item from the list widget is shown 
in the statusbar. 
</p>

<pre class="explanation">
final Label status = new Label(shell, SWT.BORDER);
status.setText("Ready");
</pre>

<p>
SWT library has no statusbar widget. We use a simple label for this. 
The label has a border.
</p>

<pre class="explanation">
FormLayout layout = new FormLayout();
shell.setLayout(layout);
</pre>

<p>
We use the <code>FormLayout</code> widget to arrange our widgets on the window. 
</p>

<pre class="explanation">
FormData labelData = new FormData();
labelData.left = new FormAttachment(0);
labelData.right = new FormAttachment(100);
labelData.bottom = new FormAttachment(100);
status.setLayoutData(labelData);
</pre>

<p>
This code will attach the status label to the bottom of the
window. Where we usually see the statusbar. 
</p>

<pre class="explanation">
final List list = new List(shell, SWT.BORDER);
</pre>

<p>
The <code>List</code> widget is created. 
</p>

<pre class="explanation">
list.add("Aliens");
list.add("Capote");
list.add("Neverending story");
list.add("Starship troopers");
list.add("Exorcist");
list.add("Omen");
</pre>

<p>
It is filled with data. 
</p>

<pre class="explanation">
list.addListener(SWT.Selection, new Listener () {
    public void handleEvent (Event e) {
        String[] items = list.getSelection();
        status.setText(items[0]);
    }
});
</pre>

<p>
We add a listener to the <code>List</code> widget. When we select
an option, the <code>handleEvet()</code> method is executed. 
In this method, we set the selected text to the status label. 
</p>

<pre class="explanation">
FormData listData = new FormData();
listData.left = new FormAttachment(shell, 30, SWT.LEFT);
listData.top = new FormAttachment(shell, 30, SWT.TOP);
list.setLayoutData(listData);
</pre>

<p>
This code puts the <code>List</code> widget at x = 30px, y = 30px.
</p>

<img src="/img/gui/swt/list.png" alt="List widget">
<div class="figure">Figure: List widget</div>



<h2>Slider</h2>

<p>
The <code>Slider</code> is a widget, that lets the user graphically select a value 
by sliding a knob within a bounded interval. Our example will show a volume control. 

</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Slider;


/**
 * ZetCode Java SWT tutorial
 *
 * In this program, we use the slider
 * widget to create a volume control
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */

public class SWTApp {

    private Shell shell;

    private Image mute;
    private Image min;
    private Image med;
    private Image max;


    public SWTApp(Display display) {

        shell = new Shell(display);
        Device dev = shell.getDisplay();

        try {
            mute = new Image(dev, "mute.png");
            min = new Image(dev, "min.png");
            med = new Image(dev, "med.png");
            max = new Image(dev, "max.png");
        } catch(Exception e) {
            System.out.println("Cannot load images");
            System.out.println(e.getMessage());
            System.exit(1);
        }
        
        shell.setText("Slider");

        initUI();

        shell.setSize(350, 200);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }


    public void initUI() {

        final Label label = new Label(shell, SWT.IMAGE_PNG);
        label.setImage(mute);
        label.pack();
        label.setLocation(240, 30);
              

        final Slider slider = new Slider(shell, SWT.HORIZONTAL);
        slider.setMaximum(100);
        slider.setBounds(30, 30, 180, 30);

        slider.addListener (SWT.Selection, new Listener () {
            public void handleEvent (Event e) {

                int value = slider.getSelection();

                if (value == 0) {
                    label.setImage(mute);
                    label.pack();
                } else if (value &gt; 0 &amp;&amp; value &lt;= 30) {
                    label.setImage(min);
                } else if (value &gt; 30 &amp;&amp; value &lt; 80) {
                    label.setImage(med);
                } else {
                    label.setImage(max);
                }
            }
        });
    }

    @Override
    public void finalize() {
        System.out.println("disposing");
        mute.dispose();
        med.dispose();
        min.dispose();
        max.dispose();
    }

    public static void main(String[] args) {
        Display display = new Display();
        SWTApp app = new SWTApp(display);
        app.finalize();
        display.dispose();
    }
}
</pre>

<p>
In the example above, we have <code>Slider</code> and 
<code>Image</code> widgets. By dragging the knob of the slider
we change the picture on the <code>Label</code> widget.
</p>

<pre class="explanation">
final Slider slider = new Slider(shell, SWT.HORIZONTAL);
slider.setMaximum(100);
</pre>

<p>
<b class="keyword">Slider</b> widget is created. Its maximum
value is 100.
</p>

<pre class="explanation">
int value = slider.getSelection();
</pre>

<p>
Inside the listener object, we obtain the
value of the slider widget. 
</p>

<pre class="explanation">
if (value == 0) {
    label.setImage(mute);
    label.pack();
} else if (value &gt; 0 &amp;&amp; value &lt;= 30) {
    label.setImage(min);
} else if (value &gt; 30 &amp;&amp; value &lt; 80) {
    label.setImage(med);
} else {
    label.setImage(max);
}
</pre>

<p>
Depending on the obtained value, we change the picture in
the label widget. 
</p>

<pre class="explanation">
@Override
public void finalize() {
    System.out.println("disposing");
    mute.dispose();
    med.dispose();
    min.dispose();
    max.dispose();
}
</pre>

<p>
We release the resources.  
</p>

<img src="/img/gui/swt/slider.png" alt="Slider widget">
<div class="figure">Figure: Slider widget</div>


<h2>Combo widget</h2>

<p>
<b class="keyword">Combo</b> is a widget that allows the user to choose from 
a drop down list of options.
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * In this program, we use the Combo
 * widget to select an option. 
 * The selected option is shown in the
 * Label widget.
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */


public class SWTApp {

    Shell shell;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Combo");

        initUI();

        shell.setSize(300, 250);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }


    public void initUI() {

        final Label label = new Label(shell, SWT.LEFT);
        label.setText("...");

        label.setLocation(50, 100);
        label.pack();

        final Combo combo = new Combo(shell, SWT.DROP_DOWN);
        combo.add("Ubuntu");
        combo.add("Fedora");
        combo.add("Mandriva");
        combo.add("Red Hat");
        combo.add("Mint");

        combo.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                label.setText(combo.getText());
                label.pack();
            };
        });


        combo.setLocation(50, 30);
        combo.pack();

    }


    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
The example shows a combo box and a label. The combo box has a list of six options. 
These are the names of Linux Distros. The label widget shows the selected option 
from the combo box. 
</p>

<pre class="explanation">
final Combo combo = new Combo(shell, SWT.DROP_DOWN);
</pre>

<p>
<code>Combo</code> widget is created.
</p>

<pre class="explanation">
combo.add("Ubuntu");
combo.add("Fedora");
combo.add("Mandriva");
combo.add("Red Hat");
combo.add("Mint");
</pre>

<p>
It is filled with data. 
</p>

<pre class="explanation">
@Override
public void widgetSelected(SelectionEvent e) {
    label.setText(combo.getText());
    label.pack();
};
</pre>

<p>
We set the selected text to the label widget.  
</p>

<img src="/img/gui/swt/combo.png" alt="Combo widget">
<div class="figure">Figure: Combo widget</div>

<p>
In this part of the Java SWT tutorial, we described some widgets of the SWT library.
</p>

<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified June 11, 2009  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
